const userService = require('../services/users')
const _ = require('../node_modules/lodash')
const moment = require('../node_modules/moment')
const { result } = require('lodash')
//*login页面 
async function login(ctx,next){
  await ctx.render('login')//*读取内容 再通过exports把内容弹出
}
async function chat(ctx,next){
//*从cookie里面拿用户名和头像并且转换成对象渲染到页面
  let {username,avatar} = JSON.parse(ctx.cookies.get('user'))
  await ctx.render('chat',{username,avatar})
}
//*接收前端发来的用户名放到cookie里
async function setCookie(ctx,next) {
    //*头像随机获取
  const avatars = [
    '/images/icon.jpg',
    '/images/icon1.jpg',
    '/images/icon2.jpg',
    '/images/icon3.jpg',
    '/images/img.jpg',
    '/images/ing.gif'
  ]
  let avatar = avatars[_.random(0,5)]
  console.log('avatar: ', avatar)
  let {username} = ctx.request.query
  let data = {
    status:'failed'
  }
//*将用户名头像转换为字符串
  if(ctx.cookies.set('user',JSON.stringify({username,avatar}))){
    data.status = 'success'
  }
//*将值返回到前端并且渲染到页面上
  ctx.response.body = data
}
async function sendMessage(ctx) {
//*将发送信息存进数据库
    // 解构
  let {content} = ctx.request.query

  let {username,avatar} = JSON.parse(ctx.cookies.get('user'))
    // console.log({username,avatar})
    //*当前时间
  let time = moment().toDate()
    //*将这些都放入数据库

  await userService.saveUser({content,username,avatar,time})
     //*将内容返回到前端带上这些元素
  ctx.response.body = {status:'success',content,username,avatar,time}
}
//*设置定时器定时从数据库获取最新消息

//*设置获取页面内一天的聊天内容
async function getContent(ctx){
    
  let times = {
    $gte:moment().subtract(1,'day').toDate(),
    $lte:moment().toDate()
  }
  let contents = await userService.timeContent(times) 
  ctx.response.body=contents
}
//*获取当前时间
async function getTime(){
  now = moment().format('YYYY年MM月DD日  hh:mm: s')
  ctx.response.body = now
}
// async function setInterval(){

// }
module.exports = {
  login,
  chat,
  setCookie,
  sendMessage,
  getContent,
  getTime,
  setInterval
}